import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "../stores/UserStore";
import LoginVue from "../views/LoginVue.vue";
import HomeVue from "../views/HomeVue.vue";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      component: LoginVue,
      name: "Login",
    },
    {
      path: "/home",
      component: HomeVue,
      meta: { requiresAuth: true }, // 需要认证
      name: "HomeVue",
      children: [
        {
          path: "user",
          name: 'UserManagement',
          component: () => import("../views/user/AllUser.vue"),
          meta: { roles: ["ROLE_admin"] }, // 仅管理员可访问
        },
        {
          path: "blank", //前面不要加斜杠
          name: 'Blank',
          component: () => import("../views/DefaultVue.vue"),
          meta: { roles: ["ROLE_admin", "ROLE_user"] }, // 管理员和普通用户可访问
        },
        {
          path: "logs", //前面不要加斜杠
          name: 'Logs',
          component: () => import("../views/logs/LoggingVue.vue"),
          meta: { roles: ["ROLE_admin", "ROLE_user"] }, // 管理员和普通用户可访问
        },
        {
          path: "docs", //前面不要加斜杠
          name: 'Docs',
          component: () => import("../views/doc/Backdoc.vue"),
          meta: { roles: ["ROLE_admin", "ROLE_user"] }, // 管理员和普通用户可访问
        },
        {
          path: "myfile", //前面不要加斜杠
          name: 'MyFile',
          component: () => import("../views/task/ProFilePdf.vue"),
          meta: { roles: ["ROLE_admin", "ROLE_user"] }, // 管理员和普通用户可访问
        },
      ],
    },
  ],
});
// 导航守卫
router.beforeEach((to, from, next) => {
    //这三个参数分别是即将要进入的路由对象、当前导航正要离开的路由、执行下一个导航钩子函数
  const userStore = useUserStore();

  // 检查是否需要认证
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!userStore.userInfo) {
      // 未登录，重定向到登录页
      next({ name: "Login" });
    } else {
      // 检查是否有权限访问该路由
      const roles = to.meta.roles as string[]; // 将 roles 强制转换为 string[]
      const premissioms = userStore.userInfo.authorityStrings || [];
      if (roles && roles.length > 0) {
        const hasPermission = roles?.some(
          (role) => premissioms.indexOf(role) >= 0
        );
        if (hasPermission) {
          next();
        } else {
          // 无权限，重定向到无权限页面
          next({ name: "HomeVue" });
        }
      } else {
        // 不需要特定角色，允许访问
        next();
      }
    }
  } else {
    // 不需要认证的路由，允许访问
    next();
  }
});
export default router;
